<template>
  <div class="article-container">
    <van-nav-bar
      title="文章详情"
      left-arrow
      @click-left="$router.back()"
    />
    <!--    文章详情-->
    <div class="article-wrap">
      <h2 class="title">{{ article.title}}</h2>
      <van-cell>
        <div slot="title">{{article.aut_name}}</div>
        <van-image
          slot="icon"
          round
          fit="cover"
          :src="article.aut_photo"
        />
        <div slot="label">{{ article.pubdate | relativeTime }}</div>
        <van-button
          round
          class="follow"
          size="small"
          :type="article.is_followed ? 'default' : 'info'"
          :icon="article.is_followed ? '' : 'plus'"
          :loading="isFollowLoading"
          @click="onFollow"
        >{{ article.is_followed ? '已关注' : '关注' }}</van-button>
      </van-cell>
      <!--      文章主体内容区域-->
      <div
        class="markdown-body"
        v-html="article.content"
        ref="article-content"
      ></div>
      <!--      文章配图预览插件-->
      <van-image-preview v-model="show" :images="images" show-index :start-position="index" />
      <!--  文章评论列表-->
      <comment-list
        :source="articleId"
        :list="commentList"
        @update-total-count="totalCommentCount = $event"
        @reply-click="onReplyClick"
      />
    </div>
    <!--    底部区域-->
    <div class="article-bottom">
      <van-button
        type="default"
        round
        size="small"
        @click="isPostShow = true"
      >写评论</van-button>
      <van-icon
        :info="totalCommentCount"
        name="comment-o"
        color="#777"
      />
      <van-icon
        :name="article.is_collected ? 'star' : 'star-o'"
        :color="article.is_collected ? 'orange' : '#777'"
        @click="onCollect"
      />
      <van-icon
        :name="article.attitude === 1 ? 'good-job' : 'good-job-o'"
        :color="article.attitude === 1 ? 'hotpink' : '#777'"
        @click="onLike"
      />
      <van-icon name="share" color="#777" @click="onShare"/>
    </div>
    <!--    发布评论-->
    <van-popup v-model="isPostShow" position="bottom">
      <post-comment
        :target="articleId"
        @post-success="onPostSuccess"
      />
    </van-popup>
    <!--    评论回复-->
    <van-popup v-model="isReplyShow" position="bottom" :style="{ height: '80%' }">
      <!-- 这里使用 v-if 的目的是让组件随着弹出层的显示进行渲染和销毁，防止加载过的组件不重新渲染导致数据不会重新加载的问题 -->
      <comment-reply
        v-if="isReplyShow"
        :comment="replyComment"
        :article-id="articleId"
        @close="isReplyShow = false"
      />
    </van-popup>
  </div>
</template>

<script>
import '../../assets/css/github-markdown.css'
import { getArticleById, addCollect, deleteCollect, addLike, deleteLike } from '../../api/article'
import { addFollow, deleteFollow } from '../../api/user'
import commentList from './comment-list'
import postComment from './post-comment'
import commentReply from './comment-reply'

export default {
  name: 'articleIndex',
  components: {
    commentList,
    postComment,
    commentReply
  },
  props: {
    articleId: {
      type: [Object, Number, String],
      required: true
    }
  },
  data () {
    return {
      article: {}, // 文章内容
      isFollowLoading: false, // 关注用户按钮的 loading 状态
      isCollectLoading: false, // 收藏的 loading 状态
      isPostShow: false, // 控制发布评论的显示状态
      commentList: [], // 文章评论列表
      totalCommentCount: 0, // 评论总数据量
      isReplyShow: false,
      replyComment: {}, // 当前回复的评论对象
      show: false, // 图片预览窗口是否显示
      index: 1,
      images: [] // 图片预览数据
    }
  },
  methods: {
    async loadArticle () {
      const { data: { data: res } } = await getArticleById(this.articleId)
      this.article = res
      // 数据改变影响视图更新（DOM数据）不是立即的
      // 所以如果需要在修改数据之后马上操作被该数据影响的视图 DOM，需要把这个代码放到 $nextTick 中
      // this.$nextTick 是 Vue 提供的一个方法
      this.$nextTick(() => {
        this.handlePreviewImage()
      })
    },
    handlePreviewImage () {
      // 1.获取文章内容 dom 容器
      const articleContent = this.$refs['article-content']
      // 2.获取所有 img 标签
      const imgs = articleContent.querySelectorAll('img')
      // 3.给 img 注册点击事件
      const imgPaths = []
      imgs.forEach((item, index) => {
        imgPaths.push(item.src)
        item.onclick = () => {
          this.images = imgPaths
          this.index = index
          this.show = true
        }
      })
    },
    async onFollow () {
      this.isFollowLoading = true
      if (this.article.is_followed) {
        // 已关注，取消关注
        await deleteFollow(this.article.aut_id)
      } else {
        await addFollow(this.article.aut_id)
      }
      this.article.is_followed = !this.article.is_followed
      this.isFollowLoading = false
    },
    async onCollect () {
      this.$toast.loading({
        message: '操作中……',
        forbidClick: true // 禁止背景点击
      })
      if (this.article.is_collected) {
        await deleteCollect(this.articleId)
      } else {
        await addCollect(this.articleId)
      }
      this.article.is_collected = !this.article.is_collected
      this.$toast.success(`${this.article.is_collected ? '' : '取消'}收藏成功！`)
    },
    async onLike () {
      this.$toast.loading({
        message: '操作中……',
        forbidClick: true
      })
      if (this.article.attitude === 1) {
        await deleteLike(this.articleId)
        this.article.attitude = -1
      } else {
        await addLike(this.articleId)
        this.article.attitude = 1
      }
      this.$toast.success(`${this.article.attitude === 1 ? '' : '取消'}点赞成功！`)
    },
    onPostSuccess (comment) {
      // 把发布成功的评论数据对象放到评论列表顶部
      this.commentList.unshift(comment)
      // 更新评论的总数量
      this.totalCommentCount++
      // 关闭发布评论弹出层
      this.isPostShow = false
    },
    onReplyClick (comment) {
      this.replyComment = comment
      // 展示回复内容
      this.isReplyShow = true
    }
    // onShare () {
    //   plus.share.sendWithSystem({ type: 'text', content: '分享内容', href: 'http://www.dcloud.io/' }, function () {
    //     console.log('分享成功')
    //   }, function (e) {
    //     console.log('分享失败：' + JSON.stringify(e))
    //   })
    // }
  },
  created () {
    this.loadArticle()
  }
}
</script>

<style scoped>
.article-wrap {
  padding: 15px;
  background-color: #FFFFFF;
  position: fixed;
  left: 0;
  right: 0;
  top: 46px;
  bottom: 44px;
  overflow-y: auto;
}
h2 {
  font-family: MicrosoftYaHei-Bold;
  font-size: 20px;
  line-height: 33px;
  letter-spacing: 1px;
  color: #3a3a3a;
  margin-bottom: 15px;
}
.van-cell {margin-bottom: 20px;}
  .van-cell .van-image {
    width: 40px;
    height: 40px;
    background-color: #034f8c;
    margin-right: 10px;
  }
  .follow {
    padding: 0 12px;
  }
  .article-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    align-items: center;
    justify-content: space-around;
    padding: 14px 0 10px;
  }
  .article-bottom .van-button {
    width: 141px;
    height: 23px;
    border: solid 1px #eeeeee;
  }
</style>
